import type { Effect, Reducer } from 'umi';

import { getConfig, getCurrent, query as queryUsers } from '@/services/user';

export type CurrentUser = {
  avater?: string;
  name?: string;
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  userid?: string;
  unreadCount?: number;
  id?: number;
};
export type CurrentConfig = {
  companyName?: string;
  address?: string;
  email?: string;
  fax?: string;
  telphone?: string;
  taxRegionCode?: string;
};
export type CurrentTenant = {
  tenancyName?: string;
  name?: string;
  isActive?: boolean;
  id?: number;
  endDate?: Date;
  effectDate?: Date;
};

export type UserModelState = {
  currentUser?: CurrentUser;
  currentConfig?: CurrentConfig;
  currentTenant?: CurrentTenant;
};

export type UserModelType = {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetch: Effect;
    fetchCurrent: Effect;
    fetchConfig: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    saveCurrentConfig: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
  };
};

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
    currentConfig: {},
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchCurrent(_, { call, put }) {
      const response = yield call(getCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *fetchConfig(_, { call, put }) {
      const response = yield call(getConfig);
      yield put({
        type: 'saveCurrentConfig',
        payload: response,
      });
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload.result.user || {},
        currentTenant: action.payload.result.tenant || {},
      };
    },
    saveCurrentConfig(state, action) {
      return {
        ...state,
        currentConfig: action.payload.result,
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default UserModel;
